package controller

import (
	"github.com/gin-gonic/gin"
	"k9-panel/app/adapter/internal"
	"k9-panel/app/response"
	"k9-panel/app/service"
	"k9-panel/app/service/dto"
	"k9-panel/config"
	"math/rand"
	"net/http"
	"strconv"
	"time"
)

var (
	Auth *AuthController
)

func init() {
	Auth = new(AuthController)
}

type AuthController struct {
}

func (t *AuthController) Login(c *gin.Context) {
	var (
		authP internal.AuthParam
	)
	if err := c.ShouldBind(&authP); err != nil {
		panic(err)
	}
	//token := dto.Token{
	//	Value: config.Cfg.Token,
	//}
	//same, err := token.Same(authP.Token)
	//if err != nil {
	//	c.JSON(http.StatusOK, response.Fail[string](err.Error()))
	//
	//}
	if config.Cfg.Token != authP.Token {
		c.JSON(http.StatusAccepted, response.Fail[string]("认证失败！"))
	}
	token := dto.Token{
		Value: config.Cfg.Token,
	}
	rand.New(rand.NewSource(time.Now().UnixNano()))
	randomNum := rand.Intn(90000) + 10000
	randomStr := strconv.Itoa(randomNum)
	authToken := token.Hash(randomStr)
	c.JSON(http.StatusAccepted, response.Success(&internal.AuthRsp{Token: authToken}))
	return
}

func (t *AuthController) Login2(c *gin.Context) {
	var (
		authP internal.AuthLoginParam
	)
	if err := c.ShouldBind(&authP); err != nil {
		panic(err)
	}
	//token := dto.Token{
	//	Value: config.Cfg.Token,
	//}
	//same, err := token.Same(authP.Token)
	//if err != nil {
	//	c.JSON(http.StatusOK, response.Fail[string](err.Error()))
	//
	//}
	//if config.Cfg.Token != authP.Token {
	//	c.JSON(http.StatusAccepted, response.Fail[string]("认证失败！"))
	//}
	account, err := service.Account.Query(c, &dto.AccountQueryParam{
		Username: authP.Username,
	})
	if err != nil {
		panic(err)
	}
	passwordHash := account.Hash(account.Salt)
	same, err := account.Same(passwordHash)
	if err != nil {
		panic(err)
	}
	if !same {
		c.JSON(http.StatusAccepted, response.Fail[string]("密码错误！"))
		return
	}
	c.JSON(http.StatusAccepted, response.Success(&internal.AuthRsp{Token: ""}))
	return
}
